package service

import (
	"context"
	"kubernate-server/conf"
	"net/http"

	"github.com/gin-gonic/gin"
	corev1 "k8s.io/api/core/v1"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)

type NameSpaceService struct {
}

type NamespaceInfo struct {
	Name              string            `json:"name"`
	Status            string            `json:"status"`
	CreationTimestamp metav1.Time       `json:"creationTimestamp"`
	Labels            map[string]string `json:"labels,omitempty"`
	Annotations       map[string]string `json:"annotations,omitempty"`
}

/*
*
创建namespace
*/
func (NameSpaceService) CreateNamespace(ctx *gin.Context) {

	namespace := &corev1.Namespace{
		ObjectMeta: metav1.ObjectMeta{
			Name: ctx.Param("nameSpace"),
		},
	}
	_, err := conf.KuberConfigSet.CoreV1().Namespaces().Create(
		context.TODO(),
		namespace,
		metav1.CreateOptions{},
	)
	if err != nil {
		ctx.JSON(http.StatusOK, gin.H{
			"messge": "failure",
		})
		return
	}
	ctx.JSON(http.StatusOK, gin.H{
		"messge": "success",
	})
}

/*
*
删除namespace
*/
func (NameSpaceService) DeleteNamespace(ctx *gin.Context) {
	var err = conf.KuberConfigSet.CoreV1().Namespaces().Delete(ctx, ctx.Param("nameSpace"), metav1.DeleteOptions{})
	if err != nil {
		ctx.JSON(http.StatusOK, gin.H{
			"messge": "failure",
		})
		return
	}
	ctx.JSON(http.StatusOK, gin.H{
		"messge": "success",
	})
}

/*
*
查询全部namespace
*/
func (NameSpaceService) GetNameSpaceList(ctx *gin.Context) {
	list, err := conf.KuberConfigSet.CoreV1().Namespaces().List(ctx, metav1.ListOptions{})
	if err != nil {
		ctx.JSON(http.StatusOK, gin.H{
			"messge": "failure",
		})
		return
	}
	var namespaceInfos []NamespaceInfo
	for _, ns := range list.Items {
		if err != nil {
			ctx.JSON(http.StatusOK, gin.H{
				"messge": "failure",
			})
			return
		}

		namespaceInfo := NamespaceInfo{
			Name:              ns.Name,
			Status:            string(ns.Status.Phase),
			CreationTimestamp: ns.CreationTimestamp,
			Labels:            ns.Labels,
			Annotations:       ns.Annotations,
		}
		namespaceInfos = append(namespaceInfos, namespaceInfo)
	}
	ctx.JSON(http.StatusOK, gin.H{
		"messge":        "success",
		"nameSpaceList": namespaceInfos,
	})
}
